package com.chao.wind3j.base.config.shiroConfig;

import com.chao.wind3j.base.apiResult.ApiCode;
import com.chao.wind3j.base.apiResult.ApiResult;
import com.chao.wind3j.base.config.commonConfig.CommonProperties;
import com.chao.wind3j.base.config.commonConfig.requestLogConfig.requestWrapper.CustomRequestWrapper;
import com.chao.wind3j.base.config.commonConfig.requestLogConfig.requestWrapper.CustomResponseWrapper;
import com.chao.wind3j.model.base.JwtToken;
import com.chao.wind3j.service.Wind3UserService;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class JwtFilter extends AuthorizationFilter {

  private final CommonProperties commonProperties;

  private final Wind3UserService wind3UserService;

  public JwtFilter(CommonProperties commonProperties, Wind3UserService wind3UserService) {
    this.commonProperties = commonProperties;
    this.wind3UserService = wind3UserService;
  }

  @Override
  public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
    return this.isAccessAllowed(request, response, mappedValue);
  }

  @SneakyThrows
  @Override
  protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
    String url = WebUtils.toHttp(request).getRequestURI();
    var customRequest = new CustomRequestWrapper(WebUtils.toHttp(request), this.commonProperties);
    var customResponse = new CustomResponseWrapper(WebUtils.toHttp(response));
    var jwtTokenString = customRequest.getRequestInfo().getAuthToken().getToken();
    var continueChain = true;
    if (this.isLoginRequest(request, response)) {
      return true;
    }
    if (StringUtils.isBlank(jwtTokenString)) {
      var apiResult = ApiResult.build("您尚未登录系统", false, ApiCode.NotLogin, null);
      customResponse.setReturnResult(apiResult);
      return false;
    }
    var jwtToken = JwtToken.build(jwtTokenString);
    var apiUser = this.wind3UserService.getUserInfoByToken(jwtTokenString);
    if (apiUser == null) {
      var apiResult = ApiResult.build("token已过期" ,false, ApiCode.TokenExpired, null);
      customResponse.setReturnResult(apiResult);
      continueChain = false;
    }
    var subject = this.getSubject(request, response);
    return continueChain;
  }
}
